<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="params.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="handleInput"
        />
        <!--
          树形组件
            highlight-current 只要你选中了某个节点 那么就会有高亮效果

            我们希望传智教育默认有高亮 => 默认需要选中 => 树形组件($refs.tree)的一个方法(setCurrentKey - 选中某个节点)

            树形组件内部 在点击节点时 $emit('node-click', 节点数据)
         -->
        <el-tree
          ref="tree"
          node-key="id"
          :data="list"
          :props="{ label: 'name' }"
          default-expand-all
          highlight-current
          :expand-on-click-node="false"
          @node-click="select"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <!-- 取决于当前这个用户role.points add-employee -->
          <!-- <el-button v-if="$store.state.user.userInfo.roles.points.includes('add-employee')" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button v-if="$store.state.user.userInfo.roles.points.includes('excel-import')" size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button v-if="$store.state.user.userInfo.roles.points.includes('excel-export')" size="mini" @click="exportFile">excel导出</el-button> -->
          <el-button v-control="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button v-control="'excel-import'" size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button v-control="'excel-export'" size="mini" @click="exportFile">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="employeeList">
          <el-table-column align="center" prop="staffPhoto" label="头像" width="80px">
            <template #default="{row}">
              <!-- {{ row.staffPhoto }} -->
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" alt="" :size="30" />

              <span v-else class="username">{{ row.username?.startsWith('黑马') ? row.username?.slice(2,3) : row.username?.slice(0,1) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="username" label="姓名" />
          <el-table-column align="center" prop="mobile" label="手机号" sortable />
          <el-table-column align="center" prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式" align="center" width="80px">
            <template #default="{row}">
              {{ row.formOfEmployment === 1 ? '正式' : '非正式' }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="departmentName" label="部门" />
          <el-table-column align="center" prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button type="text" size="mini" @click="$router.push('/employee/detail/'+ row.id)">查看</el-button>
              <el-button type="text" size="mini" @click="openRoleDialog(row.id)">角色</el-button>
              <el-popconfirm title="你确定要删除么?" @onConfirm="del(row.id)">
                <el-button slot="reference" style="margin-left: 10px" type="text" size="mini">删除</el-button>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" style="margin-top: 20px">
          <!--
            点击页码 组件内部 $emit('current-change', 最新页码)
           -->
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            :current-page="params.page"
            :page-size="params.pagesize"
            @current-change="handleCurrentChange"
          />
        </el-row>

        <!-- {{timeId}} -->
      </div>
    </div>

    <!-- 导入excel -->
    <ImportExcel
      :show-excel-dialog.sync="showExcelDialog"
      @refresh="getEmployeeList"
    />

    <!-- 分配角色的dialog -->
    <el-dialog :visible.sync="showRoleDialog" title="分配角色" @close="close">
      <!-- 多选型的多选框(爱好) -->
      <el-checkbox-group v-model="checkList">
        <!-- ele组件库的不友好:   label 文字描述   value 对应的值 -->
        <!-- 正常情况下: label既文字描述又对应的值 -->
        <!-- 还有一种情况: label只当值   插槽填文字描述 -->
        <el-checkbox
          v-for="item in enabledRoleList"
          :key="item.id"
          :label="item.id"
        >{{ item.name }}</el-checkbox>
      </el-checkbox-group>

      <el-row type="flex" justify="center">
        <el-button type="primary" size="mini" @click="assignRoles">确定</el-button>
        <el-button size="mini" @click="close">取消</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentList } from '@/api/department'
import { exportEmployeeList, getEmployeeList, delEmployee, getEmployeeDetail, assignRoles } from '@/api/employee'
import { getEnabledRoleList } from '@/api/role'
import { getTreeFromList } from '@/utils'
import { saveAs } from 'file-saver'
import ImportExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  directives: {

  },
  data() {
    return {
      // 提供在data中的数据 会有响应式效果 => 数据一变 页面会变化
      list: [], // 部门树形数据
      employeeList: [], // 员工列表
      total: 0,
      // page: ,
      // pagesize:
      params: {
        page: 1,
        pagesize: 10,
        departmentId: 1, // 传智教育的id是1
        keyword: ''
      },
      showExcelDialog: false,
      showRoleDialog: false,

      enabledRoleList: [], // 可选的角色列表
      checkList: [], // 选中的角色列表
      currentId: ''

      // timerId: null // 定时器id 是不需要响应式效果的
    }
  },
  created() {
    this.getDepartList()
    this.getEmployeeList()
  },
  methods: {
    async assignRoles() {
      await assignRoles(this.currentId, this.checkList)
      this.$message.success('分配成功')
      // 关dialog + 清空
      this.close()
    },
    close() {
      this.showRoleDialog = false
      this.checkList = [] // 清空选中项
    },
    async openRoleDialog(id) {
      // id => 当前员工id
      this.currentId = id
      // 获取启用的角色列表
      this.enabledRoleList = await getEnabledRoleList()
      // 获取用户的基本信息(包含选中的角色列表)
      const { roleIds } = await getEmployeeDetail(id)
      this.checkList = roleIds
      // 打开dialog
      this.showRoleDialog = true
    },
    async del(id) {
      // 调用请求函数(封装) => 提示 => 重新加载数据渲染页面(本页最后一条)
      await delEmployee(id)
      this.$message.success('删除用户成功')
      if (this.employeeList.length === 1 && this.params.page > 1) this.params.page--
      this.getEmployeeList()
    },
    async exportFile() {
      // 下载文件: file-saver => saveAs下载文件
      // saveAs(二进制文件流Blob, 文件名)
      // const blob = new Blob(['Hello, world!'], { type: 'text/plain;charset=utf-8' })
      const blob = await exportEmployeeList()
      saveAs(blob, '黑马112期员工列表.xlsx')
    },
    handleInput() {
      // 防抖 => 所有的逻辑都丢在延时器中 高频触发时 清空上一次的延时器逻辑
      clearTimeout(this.timerId)
      this.timerId = setTimeout(() => {
        // console.log('发请求啦')
        this.params.page = 1 // 重置页码
        this.getEmployeeList() // 获取员工数据
      }, 300)
    },
    handleCurrentChange(val) {
      this.params.page = val
      this.getEmployeeList()
    },
    select({ id }) {
      // console.log('节点被点击了', val)
      this.params.departmentId = id
      this.getEmployeeList()
    },
    async getDepartList() {
      const res = await getDepartmentList()
      // console.log(res)
      this.list = getTreeFromList(res, 0) // 部门列表数据 => 树形组件渲染好了(不是立即渲染好的) => 选中默认的传智教育 id=1

      // 等树形组件渲染完毕
      this.$nextTick(() => {
        // 必须设置node-key="id"属性
        this.$refs.tree.setCurrentKey(1) // 选中
      })
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.params)
      this.total = total
      this.employeeList = rows
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
